package com.example.demo.identity.application;

import com.example.demo.identity.application.dtos.IdentityUserDto;
import com.example.demo.identity.application.dtos.IdentityUserFilter;
import com.example.demo.identity.domain.IdentityUser;
import com.example.demo.identity.domain.IdentityUserRepository;
import com.example.jbp.application.dtos.PagedResultDto;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class IdentityUserAppService {
    private final IdentityUserRepository repository;

    public IdentityUserAppService(IdentityUserRepository repository) {
        this.repository = repository;

        IdentityUser model = new IdentityUser(UUID.fromString("095c64fe-c5bf-11ea-aec6-a402b9e2b04d"));
        model.setUserName("admin");
        model.setName("panpeizhao");
        model.setSurname("ppz");
        this.repository.save(model);
    }

    public PagedResultDto<IdentityUserDto> pageList(@NotNull IdentityUserFilter filter, Pageable pageable) {
        Page<IdentityUser> pageEntities = repository.pageList(filter.getUserName(), pageable);
        List<IdentityUserDto> dtos = pageEntities.toList().stream().map(item -> {
            IdentityUserDto dto = new IdentityUserDto();
            BeanUtils.copyProperties(item, dto);
           return dto;
        }).collect(Collectors.toList());
        return new PagedResultDto<>(dtos.size(), dtos);
    }

    public IdentityUserDto get(UUID id) {
        Optional<IdentityUser> entity = this.repository.findById(id);
        IdentityUserDto dto = null;
        if (entity.isPresent()) {
            BeanUtils.copyProperties(entity.get(), dto = new IdentityUserDto());
        }
        return dto;
    }
}
